/**
 * @file shell_port.c
 * @author Letter (NevermindZZT@gmail.com)
 * @brief
 * @version 0.1
 * @date 2019-02-22
 *
 * @copyright (c) 2019 Letter
 *
 */

#include "shell_port.h"
#include "main.h"
#include "shell.h"
#include "stm32f4xx_ll_usart.h"

Shell shell;
char shellBuffer[512];

/**
 * @brief 用户shell写
 *
 * @param data 数据
 * @param len 数据长度
 *
 * @return short 实际写入的数据长度
 */
short userShellWrite(char* data, unsigned short len)
{
    uint32_t timeout = 100;
    uint32_t tx_len = 0;
    uint8_t tmp = 0;

    for (uint32_t i = 0; i < len; i++) {
        while ((timeout != 0U) && (tmp != 1U)) {
            if (LL_SYSTICK_IsActiveCounterFlag() == 1U) {
                timeout--;
                if (timeout == 0U) {
                    return tx_len;
                }
            }
            tmp = LL_USART_IsActiveFlag_TXE(USART1);
        }
        LL_USART_TransmitData8(USART1, *(data + i));
        tmp = 0;
        tx_len++;
    }

    return tx_len;
}

/**
 * @brief 用户shell读
 *
 * @param data 数据
 * @param len 数据长度
 *
 * @return short 实际读取到
 */
short userShellRead(char* data, unsigned short len)
{
    uint32_t timeout = 100;
    uint32_t rx_len = 0;
    uint8_t tmp = 0;

    for (uint32_t i = 0; i < len; i++) {
        while ((timeout != 0U) && (tmp != 1U)) {
            if (LL_SYSTICK_IsActiveCounterFlag() == 1U) {
                timeout--;
                if (timeout == 0U) {
                    return rx_len;
                }
            }
            tmp = LL_USART_IsActiveFlag_RXNE(USART1);
        }
        *(data + i) = LL_USART_ReceiveData8(USART1);
        tmp = 0;
        rx_len++;
    }

    return rx_len;
}

/**
 * @brief 用户shell初始化
 *
 */
void userShellInit(void)
{
    shell.write = userShellWrite;
    shell.read = userShellRead;
    shellInit(&shell, shellBuffer, 512);
}
